<template>
  <div>
    <upload-excel style="margin-top: 70px;" :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils'
import { importEmployees } from '@/api/employees'
export default {
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 上传
    async  handleSuccess({ results, header }) {
      // console.log('这是上传的结果:', results, header)
      // console.log('这是转为英文的结果:', this.transExcel(results))
      const data = this.transExcel(results)
      try {
        // 发送请求
        const res = await importEmployees(data)
        // 提醒用户
        this.$message.success(res.message)
        // 返回上一步
        this.$router.back()
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    transExcel(results) {
      // 数据映射
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // 遍历数组
      return results.map(zhObj => {
        const enObj = {}
        // 拿到数组中所有中文的key值
        const zhKeys = Object.keys(zhObj)
        // 将中文的key值转化为英文的key
        zhKeys.forEach(zhKey => {
          // 根据入职日期中文，取出响应的英文
          const enkey = mapInfo[zhKey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            enObj[enkey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            // 添加到enObj中 拼装成英文key
            enObj[enkey] = zhObj[zhKey]
          }
        })
        return enObj
      })
    }
  }
}
</script>

<style>

</style>
